package com.ruoyi.common.utils.rsa;

import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author luobo
 * @title: RSAUtil
 * @projectName pos
 * @description: TODO
 * @date 2021-11-09 08:29:11
 */
public class RSAUtil {
    private static final String SIGN_TYPE_RSA = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String SIGN_ALGORITHMS_256 = "SHA256WithRSA";
    private RSAUtil() {

    }
    /*** 验签
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @return 是否验签通过 */
    private static boolean verify(byte[] srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(SIGN_TYPE_RSA);
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(key);
        signature.update(srcData);
        return signature.verify(Base64.getUrlDecoder().decode(sign));
    }
    public static boolean verify(byte[] srcData, String publicKeystr, String sign) throws Exception {
        PublicKey publicKey = getPublicKeyFromX509(SIGN_TYPE_RSA, publicKeystr);
        return verify(srcData, publicKey, sign);
    }
    public static boolean verify(String srcData, String publicKeystr, String sign) throws Exception {
        PublicKey publicKey = getPublicKeyFromX509(SIGN_TYPE_RSA, publicKeystr);
        return verify(srcData.getBytes(StandardCharsets.UTF_8), publicKey, sign);
    }
    /** 通过证书获取公钥（需 BASE64，X509 为通用证书标准）
     * @param algorithm
     * @param base64PubKey
     * @throws Exception */
    public static PublicKey getPublicKeyFromX509(String algorithm, String base64PubKey) throws Exception {
        if (algorithm == null || "".equals(algorithm) || base64PubKey == null || "".equals(base64PubKey)) {
            return null;
        }
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(base64PubKey)));
    }
    public static byte[] sign(byte[] data, String privateKey) throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(decoder.decode(privateKey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initSign(priKey);
        signature.update(data);
        return signature.sign();
    }
    /*** 生成签名
     * @param data
     * @param privateKey
     * @return
     * @throws Exception */
    public static String sign(String data, String privateKey) throws Exception {
        return Base64.getUrlEncoder().withoutPadding().encodeToString(sign(data.getBytes(), privateKey));
    }
    public static void main(String[] args) throws Exception {
        String bodystr = "{\"agentId\":\"CS4027038\",\"merName\":\"俊俊杂货铺\",\"merId\":\"980907910800298\",\"merUsername\":\"俊俊 \",\"merPhone\":\"151****1740\",\"screenNum\":\"62**********3479\",\"createTime\":\"20210531151759\",\"merchantType\":1,\"bindStatus\":1,\"snCode\":\"CS000005936\"}";
        String sign = "gataaY1oQ-JrzGww1aN9vEGuc7-3BlLD-dQ2YGeRP098jEfE1hYmO4_iE6bTYn-EX_E6HHhu-oSss_B8mu9kD9iBb29KOtG-HoOGDffTmFxt_Kp_cXjH0iTT5RR5qM2DzxwH-KAjn2g1H1Lxj2epgxN89yDJ6CJ3SBIcevjC6_w";
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrs/f08GfpbDJ0uoGdZBNXThl7SCTFd8tGJfxkvzrAEWR1DRMzQHArzQK8CKq1FBVGxBXUjXoSw3TD7JxMeXIhmt9Pf2/yNc6gzPDPZXKQG287Xu7Sy4dXTApJx4DlOc2hprxjrcx54vXbQRpgqvBAngLCAB6ZV/C5Gwg5fX rSsQIDAQAB";
        boolean verify = verify(bodystr, publicKey, sign);
        System.out.println("验证：" + verify);
    }
}
